package com.workingpub.commons.orm.internal;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.JoinTable;

import org.springframework.util.StringUtils;

import com.workingpub.commons.domain.Identifiable;
import com.workingpub.commons.domain.UnDeletable;
import com.workingpub.commons.orm.SqlBuildEntry;

public class DeleteBuilder extends AbstractSqlBuilder {

	public <T extends Identifiable<?>> DeleteBuilder(Class<T> type) {
		super(type);
	}

	@Override
	protected <T extends Identifiable<?>> SqlBuildEntry build(EntityMetaInfo metaInfo, T entity) throws Exception {
		SqlBuildEntry sqlEntry = null;

		// 逻辑删除简单实现，字段名必须为is_deleted
		if (entity instanceof UnDeletable) {
			// String realTable = getUnDeletableTable(metaInfo);
			if (!metaInfo.containsColumnKey(UnDeletable.Deleted_Flag_Field)) {
				return null;
			}
			sqlEntry = new SqlBuildEntry();
			sqlEntry.append("Update " + metaInfo.getTableName())
					.append(" Set " + UnDeletable.Deleted_Flag_Field + " = 1").append(" Where " + metaInfo.getIdname())
					.append(" = :" + metaInfo.getIdname());
			sqlEntry.putParam(metaInfo.getIdname(), entity.getId());
		} else {
			sqlEntry = new SqlBuildEntry();
			sqlEntry.append("Delete From " + metaInfo.getTableName()).append(" Where ").append(metaInfo.getIdname())
					.append(" = :" + metaInfo.getIdname());
			sqlEntry.putParam(metaInfo.getIdname(), entity.getId());
		}

		return sqlEntry;
	}

	@Override
	protected <T extends Identifiable<?>> List<SqlBuildEntry> buildManyToMany(Field field, T entity) throws Exception {
		JoinTable joinTable = field.getAnnotation(JoinTable.class);
		return buildManyToMany(joinTable, field, entity);
	}

	@Override
	protected <T extends Identifiable<?>> List<SqlBuildEntry> buildManyToMany(PropertyDescriptor property, T entity)
			throws Exception {
		JoinTable joinTable = property.getReadMethod().getAnnotation(JoinTable.class);
		return buildManyToMany(joinTable, property, entity);
	}

	private <T extends Identifiable<?>> List<SqlBuildEntry> buildManyToMany(JoinTable joinTable, Object value, T entity)
			throws Exception {
		// 逻辑删除不删除关系
		if (entity instanceof UnDeletable) {
			return null;
		}
		if (StringUtils.isEmpty(entity.getId())) {
			logger.warn("Entity id is null, build failed.");
			return null;
		}
		String tableName = joinTable.name();
		String joinColumn = joinTable.joinColumns()[0].name();

		List<SqlBuildEntry> sqlEntries = new ArrayList<SqlBuildEntry>();
		SqlBuildEntry removeEntry = new SqlBuildEntry();
		removeEntry.append("Delete From " + tableName).append(" Where ").append(joinColumn).append(" = :" + joinColumn);
		removeEntry.putParam(joinColumn, entity.getId());
		sqlEntries.add(removeEntry);

		return sqlEntries;
	}

}
